from boa.interop.System.ExecutionEngine import GetScriptContainer, GetExecutingScriptHash
from boa.interop.System.Storage import GetContext, Get, Put, Delete

Push = RegisterAction('event', 'operation', 'msg')


def Main(operation, args):
    if operation == 'QueryProduct':
        productid = args[0]
        return QueryProduct(productid)

    if operation == 'AddProduct':
        productid = args[0]
        owner = args[1]
        return AddProduct(productid, owner)

    if operation == 'TransferProduct':
        productid = args[0]
        to = args[1]
        return TransferProduct(productid, to)

    return False


def QueryProduct(productid):
    context = GetContext()
    owner = Get(context, productid);

    Push('query', productid)
    if owner == None:
        return False

    return owner


def AddProduct(productid, owner):
    context = GetContext()
    occupy = Get(context, productid);
    if occupy != None:
        return False;
    Put(context, productid, owner)
    Push('AddProduct', productid, owner)
    return True


def TransferProduct(productid, to):
    if to == None:
        return False

    context = GetContext()
    owner = Get(context, productid)
    if owner == None:
        return False
    if owner == to:
        return True

    # is_owner = CheckWitness(owner)

    # if not is_owner:
    #    return False

    Put(context, productid, to)
    Push('TransferProduct', productid)

    return True
